package me.leon.aoplib;

import android.util.Log;
import android.view.View;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;

/**
 * <p>description：</p>
 * <p>author：Leon</p>
 * <p>date：2019/8/29 0029</p>
 * <p>e-mail：deadogone@gmail.com</p>
 */
@Aspect
public class LeonAop {

    @Pointcut("execution(@me.leon.aoplib.SingleClick * *(..))")
    public void clickFilter() {
    }

    @Around("clickFilter()")
    public void injectClick(ProceedingJoinPoint joinPoint) throws Throwable {
// 取出方法的参数
        View view = null;
        for (Object arg : joinPoint.getArgs()) {
            if (arg instanceof View) {
                view = (View) arg;
                break;
            }
        }
        if (view == null) {
            return;
        }

        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        if (!method.isAnnotationPresent(SingleClick.class)) {
            return;
        }
        SingleClick singleClick = method.getAnnotation(SingleClick.class);
        // 判断是否快速点击
        if (!ClickUtils.getInstance().isFastDoubleClick(view, singleClick.value())) {
            // 不是快速点击，执行原方法
            joinPoint.proceed();
        } else {
            Log.d("AOP", "快速 click 过滤 : " + joinPoint.getSignature().getName());
            return;
        }
        Log.d("AOP", "click : " + joinPoint.getSignature().getName());
    }

    @Pointcut("execution(@me.leon.aoplib.TimeTakes * *(..))")
    public void timeCount() {
    }

    @Around("timeCount()")
    public void timeHandle(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        if (!method.isAnnotationPresent(TimeTakes.class)) {
            return;
        }
        TimeTakes timeTakes = method.getAnnotation(TimeTakes.class);
        long start = System.currentTimeMillis();
        joinPoint.proceed();
        long end = System.currentTimeMillis();
        Log.d("AOP", joinPoint.getSignature().getName() + "  time takes (ms) : " + (end - start));
    }

}
